﻿using AutoMapper;
using MediatR;
using Management.API.Application.Controller.Management;
using Management.Domain;
using Management.Errorcode;
using Management.Errorcode.ErrorCode;
using Management.Infrastructure.Interfaces;
using Management.Infrastructure.Interfaces.BOMManagement;
using Management.Models.BOMBasicInformation;
using Management.API.Application.Controller.Management.Material;


namespace Management.API.Application.CommandHandler
{
    
    public class AddMaterialCommandHandler : IRequestHandler<AddMaterialCommand, ApiResult>
    {

        private readonly IMaterialRepository _iMaterialRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddMaterialCommandHandler> _logger;

        public AddMaterialCommandHandler(IMaterialRepository IMaterialRepository, IMapper mapper, ILogger<AddMaterialCommandHandler> logger)
        {
            _iMaterialRepository = IMaterialRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult> Handle(AddMaterialCommand request, CancellationToken cancellationToken)
        {

            try
            {
                // 将 DTO 映射为实体类
                var userEntity = _mapper.Map<Material>(request);

                // 调用仓储层添加BOM
                var addedUser = await _iMaterialRepository.InsertAsync(userEntity);

                // 返回成功结果
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加BOM失败");
                return ApiResult.Fail("添加BOM失败", StatusCodeEnum.InternalServerError);
            }
        }



    }
}


